package com.openNetty.common.system;

import org.apache.commons.lang.StringUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

/**
 * @author zhenggm
 * @create 2017-11-20 下午 4:18
 **/


public class FileUtils {
    /**
     * 使用零拷贝复制文件内容
     *
     * @param from 从这个文件复制数据
     * @param to   把复制的数据写入到这个文件
     * @throws IOException
     */
    public static void zeroCopy(File from, File to) throws IOException {
        FileChannel fromChannel = null;
        FileChannel toChannel = null;
        try {
            fromChannel = new FileInputStream(from).getChannel();
            toChannel = new FileOutputStream(to).getChannel();
            toChannel.transferFrom(fromChannel, 0, fromChannel.size());
        } finally {
            if (fromChannel != null) fromChannel.close();
            if (toChannel != null) toChannel.close();
        }
    }

    /**
     * 使用零拷贝复制文件内容,拼接到当前文件后
     *
     * @param from 从这个文件复制数据
     * @param to   把复制的数据写入到这个文件
     * @throws IOException
     */
    public static void zeroAppend(File from, File to) throws IOException {
        FileChannel fromChannel = null;
        FileChannel toChannel = null;
        try {
            fromChannel = new FileInputStream(from).getChannel();
            toChannel = new FileOutputStream(to, true).getChannel();
            toChannel.transferFrom(fromChannel, toChannel.size(), fromChannel.size());
        } finally {
            if (fromChannel != null) fromChannel.close();
            if (toChannel != null) toChannel.close();
        }
    }

    /**
     * 删除文件,如果是目录则删除目录和目录下的子
     *
     * @param file 删除的文件对象
     * @author shuim
     * @date 2016/4/13
     */
    public static boolean deleteFile(File file) {
        try {
            if (file.exists()) {
                if (file.isDirectory()) {
                    boolean result = true;
                    for (File subFile : file.listFiles()) {
                        if (!FileUtils.deleteFile(subFile)) {
                            result = false;
                        }
                    }
                    if (!file.delete()) {
                        result = false;
                    }
                    return result;
                } else {
                    return file.delete();
                }
            } else {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 重命名文件
     */
    public static void renameFileByName(File oldFile, String name)
            throws IOException {
        oldFile.renameTo(new File(oldFile.getParentFile().getCanonicalPath()
                + File.separator + name));
    }

    /**
     * 根据没有后缀的文件名重命名文件
     */
    public static void renameFileByNameWithoutExtention(File oldFile,
                                                        String nameWithoutExtention) throws IOException {
        if (oldFile.isDirectory()) {
            FileUtils.renameFileByName(oldFile, oldFile.getName());
        } else {
            String extension = FileUtils.getFileExtension(oldFile.getName());
            FileUtils.renameFileByName(oldFile, nameWithoutExtention + "."
                    + extension);
        }
    }

    /**
     * 拼接路径
     */
    public static String getPath(String dir, String fileNameWithoutExtension,
                                 String extension) {
        StringBuffer path = new StringBuffer(getPath(dir,
                fileNameWithoutExtension));
        path.append(".");
        path.append(extension);
        return path.toString();
    }

    /**
     * 拼接路径
     */
    public static String mergePath(String dir, String dir2) {
        if (dir == null) {
            return dir2;
        } else {
            if (dir2 == null) return dir;
            StringBuilder path = new StringBuilder(dir);
            if (dir.endsWith(File.separator)) {
                if (dir2.startsWith(File.separator)) {
                    path.append(dir2.substring(1));
                } else {
                    path.append(dir2);
                }
            } else {
                if (dir2.startsWith(File.separator)) {
                    path.append(dir2);
                } else {
                    path.append(File.separator).append(dir2);
                }

            }
            return path.toString();
        }
    }

    /**
     * 拼接路径
     */
    public static String getPath(String dir, String fileName) {
        StringBuffer path = new StringBuffer(dir);
        path.append(File.separator);
        path.append(fileName);
        return path.toString();
    }

    /**
     * 拼接文件后缀
     */
    public static String addFileExtension(String fileNameWithoutExtension,
                                          String fileExtension) {
        if (StringUtils.isNotEmpty(fileNameWithoutExtension)) {
            StringBuffer sb = new StringBuffer(fileNameWithoutExtension);
            sb.append(".");
            sb.append(fileExtension);
            return sb.toString();
        } else {
            return "";
        }
    }

    /**
     * 替换文件（必须是单个文件对象，不能是路径）后缀
     *
     * @param fileName      文件名
     * @param fileExtension 后缀
     * @return
     */
    public static String replaceFileExtension(String fileName,
                                              String fileExtension) {
        if (StringUtils.isNotEmpty(fileName)) {
            if (fileName.lastIndexOf(".") >= 0) {
                StringBuffer sb = new StringBuffer(
                        getFileNameWithoutExtension(fileName));
                sb.append(".");
                sb.append(fileExtension);
                return sb.toString();
            } else {
                return fileName;
            }
        } else {
            return "";
        }
    }

    /**
     * 取得文件（必须是单个文件对象，不能是路径）后缀
     *
     * @param fileName
     * @return
     */
    public static String getFileExtension(String fileName) {
        if (StringUtils.isNotEmpty(fileName) && fileName.lastIndexOf(".") >= 0
                && !fileName.endsWith(".")) {
            return fileName.substring(fileName.lastIndexOf(".") + 1);
        } else {
            return "";
        }
    }

    /**
     * 取得文件（必须是单个文件对象，不能是路径）无后缀的名字
     *
     * @param fileName
     * @return
     */
    public static String getFileNameWithoutExtension(String fileName) {
        if (StringUtils.isNotEmpty(fileName)) {
            int index = fileName.lastIndexOf(".");
            if (index >= 0) {
                return fileName.substring(0, fileName.lastIndexOf("."));
            } else {
                return fileName;
            }
        } else {
            return "";
        }
    }

    /**
     * 获取path2相对path1的相对路径
     * path2是path1的子路径
     *
     * @param
     * @return
     * @throws
     */
    public static String getRelativePath(String path1, String path2) {
        if (path2.startsWith(path1)) {
            return path2.substring(path1.length());
        }
        return null;
    }
}
